package com.tvunetworks.center.device.jms;

import com.tvunetworks.center.device.service.PidPortMappingService;
import com.tvunetworks.center.device.service.UserDeviceService;
import com.tvunetworks.center.device.service.feign.DeviceExtraFeign;
import com.tvunetworks.center.device.service.feign.WebsocketFeignService;
import com.tvunetworks.leader.election.starter.LeaderElection;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.stereotype.Component;

import javax.jms.ConnectionFactory;
import javax.jms.Session;

/**
 * @program: tvucc-aggregator
 * @description: MQConsumer
 * @author lebronchen
 * @create: 2019-11-05 14:45
 **/
@Component
@Slf4j
public class MQConsumer {

    private  static final  Logger LOGGER = LoggerFactory.getLogger("message");

    @Autowired
    private WebsocketFeignService websocketFeignService;
    @Autowired
    @Qualifier("deviceChangeElection")
    private LeaderElection leaderElection;
    @Autowired
    private PidPortMappingService pidPortMappingService;
    @Autowired
    private UserDeviceService userDeviceService;

    @Value("${enableDeviceChangeNotify}")
    private boolean enableDeviceChangeNotify;
    @Value("${showDeviceChangeMQLog}")
    private boolean showDeviceChangeMQLog;
    @Value("${mpStatusChangeTopic}")
    private String mpStatusChangeTopic;
    @Value("${deviceChangeMQRecoveryInterval}")
    private Long deviceChangeMQRecoveryInterval;
    @Value("${deviceChangeMQClientId}")
    private String deviceChangeMQClientId;

    @Value("${enable.notifyReceiverOnline}")
    private boolean enableNotifyReceiverOnline;

    @Value("${MQ.sendMessage.switch}")
    private boolean switchs;

    @Autowired
    private DeviceExtraFeign deviceExtraFeign;
    /**
     *
     * @param connectionFactory connectionFactory
     * @return JmsListenerContainerFactory
     */
    @Bean("jmsTopicListenerContainerFactory")
    public JmsListenerContainerFactory jmsTopicListenerContainerFactory(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        //重连间隔时间
        factory.setRecoveryInterval(deviceChangeMQRecoveryInterval);
        factory.setPubSubDomain(true);
        // 给订阅者一个名字,并开启订阅
        factory.setClientId(deviceChangeMQClientId);
        factory.setSubscriptionDurable(false);
        factory.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
        return factory;
    }

    /**
     *
     * @param message message
     */
    @JmsListener(destination = "${mpStatusChangeTopic}", containerFactory = "jmsTopicListenerContainerFactory")
    public void receive(String message) {
        if (!leaderElection.isMaster()) {
            log.info("MQConsumer receive leader election not master");
            return;
        }
        if (!enableDeviceChangeNotify) {
            return;
        }
        // 新增flag，并且打日志到新的文件中
        if (showDeviceChangeMQLog) {
            LOGGER.error(message);
        }

        try {
            if(switchs){
                //封装数据,发送到mq
                userDeviceService.deviceStatusChanged(message);
            }

            websocketFeignService.notifyDeviceChange(message);
        } catch (Exception e) {
            LOGGER.error(e.toString(), e);
        }
        try {
            pidPortMappingService.receiverStatusChanged(message);
        } catch (Exception e) {
            log.error("MQConsumer>>>>>receiver  pidPortMappingService receiverStatusChanged exception", e);
        }

    }

}
